<template>
  <div class="users_container">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 主体 -->
    <el-card class="box-card">
      <!-- 头部操作区 -->
      <el-row class="card-header"
        :gutter="20">
        <!-- 搜索用户 -->
        <el-col :span="12">
          <el-input placeholder="查找用户"
            clearable
            v-model="getParams.query"
            @clear="clearSearch">
            <el-button slot="append"
              icon="el-icon-search"
              @click="getUsersList"></el-button>
          </el-input>
        </el-col>
        <!-- 添加用户 -->
        <el-col :span="12">
          <el-button type="primary"
            :span="12"
            @click="dialogVisible = true">添加用户</el-button>
        </el-col>
        <!-- 弹窗 -->
        <el-dialog title="添加用户"
          :visible.sync="dialogVisible">
          <!-- 用户信息表单 -->
          <el-form ref="newUserForm"
            :model="newUserForm"
            label-width="auto"
            :rules="newUserRules"
            status-icon>
            <el-form-item label="用户名"
              prop="username">
              <el-input v-model="newUserForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码"
              prop="password">
              <el-input type="password"
                v-model="newUserForm.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱"
              prop="email">
              <el-input v-model="newUserForm.email"></el-input>
            </el-form-item>
            <el-form-item label="电话"
              prop="mobile">
              <el-input v-model="newUserForm.mobile"></el-input>
            </el-form-item>
          </el-form>
          <!-- 底部操控区域 -->
          <div slot="footer">
            <el-button @click="closeDialogUser('newUserForm')">取 消</el-button>
            <el-button type="primary"
              @click="submitDialogUser">确 定</el-button>
          </div>
        </el-dialog>
      </el-row>

      <!-- 数据表格 -->
      <el-table :data="usersList"
        border>
        <el-table-column prop="id"
          label="id"
          align="center"> </el-table-column>
        <el-table-column prop="username"
          label="姓名"
          align="center"> </el-table-column>
        <el-table-column prop="mobile"
          label="电话"
          align="center"> </el-table-column>
        <el-table-column prop="role_name"
          label="角色"
          align="center"> </el-table-column>
        <!-- 状态修改 -->
        <el-table-column label="状态"
          width="160"
          align="center">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state"
              @change="changeUserStatus(scope)"></el-switch>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column label="操作"
          width="210"
          align="center">
          <template slot-scope="scope">
            <!-- 修改信息按钮 -->
            <el-button size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editUser(scope.row)"></el-button>
            <!-- 修改用户信息弹窗 -->
            <el-dialog title="修改用户信息"
              :visible.sync="editdialogVisible">
              <!-- 用户信息表单 -->
              <el-form ref="editUserForm"
                :model="editUserForm"
                label-width="auto"
                :rules="newUserRules"
                status-icon>
                <el-form-item label="用户名"
                  prop="username">
                  <el-input v-model="editUserForm.username"
                    :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="邮箱"
                  prop="email">
                  <el-input v-model="editUserForm.email"></el-input>
                </el-form-item>
                <el-form-item label="电话"
                  prop="mobile">
                  <el-input v-model="editUserForm.mobile"></el-input>
                </el-form-item>
              </el-form>
              <!-- 底部操控区域 -->
              <div slot="footer">
                <el-button @click="closeEditUser('editUserForm')">取 消</el-button>
                <el-button type="primary"
                  @click="submitEdit">确 定</el-button>
              </div>
            </el-dialog>
            <!-- 删除用户按钮 -->
            <el-button size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="deleteUser(scope.row.id)"></el-button>
            <!-- 分配权限按钮 -->
            <el-tooltip effect="dark"
              content="分配权限"
              placement="top-start"
              :enterable="false">
              <el-button size="mini"
                type="warning"
                icon="el-icon-key"
                @click="setUserRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination layout="total, sizes, prev, pager, next, jumper"
        :current-page="getParams.pagenum"
        :page-sizes="[2, 4, 6]"
        :page-size="getParams.pagesize"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"> </el-pagination>

      <!-- 分配权限角色对话框 -->
      <el-dialog title="分配权限角色"
        :visible.sync="roleDialogVisible">
        <!-- 用户信息表单 -->
        <el-form ref="userRoleForm"
          :model="userRoleForm"
          label-width="auto"
          status-icon>
          <el-form-item label="用户名">
            <el-input v-model="userRoleForm.username"
              :disabled="true"></el-input>
          </el-form-item>

          <el-form-item label="权限角色">
            <el-select v-model="userRoleForm.rid"
              placeholder="请选择">
              <el-option v-for="item in roleOptions"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"> </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <!-- 底部操控区域 -->
        <div slot="footer">
          <el-button @click="roleDialogVisible = false">取 消</el-button>
          <el-button type="primary"
            @click="submitUserRole">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Users',
  data() {
    const checkMail = (rule, value, callback) => {
      const regEMail = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/

      if (regEMail.test(value)) {
        callback()
      }

      callback(new Error('请输入合法邮箱'))
    }
    const checkMobile = (rule, value, callback) => {
      const regMobile = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/

      if (regMobile.test(value)) {
        callback()
      }

      callback(new Error('请输入合法手机号'))
    }
    return {
      // get参数
      getParams: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      total: 0,
      // 用户列表
      usersList: [],
      //
      dialogVisible: false,
      // 新用户
      newUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 验证规则
      newUserRules: {
        username: [
          { required: true, message: '请输入新用户名', trigger: 'blur' },
          { min: 3, max: 7, message: '长度在 3 到 7 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: checkMail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 修改用户信息
      editdialogVisible: false,
      editUserForm: {
        id: 0,
        username: '',
        email: '',
        mobile: ''
      },
      // 分配角色
      roleDialogVisible: false,
      roleOptions: [],
      userRoleForm: {
        username: '',
        rid: ''
      },
      userId: 0
    }
  },
  created() {
    // 请求用户列表数据
    this.getUsersList()
  },
  methods: {
    // 请求用户数据列表
    async getUsersList() {
      const { data: res } = await this.$http.get('users', {
        params: this.getParams
      })

      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.usersList = res.data.users
      this.getParams.pagenum = res.data.pagenum
      this.total = res.data.total
    },
    // 改变用户状态
    async changeUserStatus(scope) {
      // console.log(scope.row)
      const { data: res } = await this.$http.put(`users/${scope.row.id}/state/${scope.row.mg_state}`)

      // console.log(res)
      if (res.meta.status !== 200) {
        scope.row.mg_state = !scope.row.mg_state
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },
    // 改变一页展示数目
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.getParams.pagesize = val
      this.getUsersList()
    },
    // 改变当前页
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.getParams.pagenum = val
      this.getUsersList()
    },
    // 清空搜索结果
    clearSearch() {
      this.query = ''
      this.getUsersList()
    },
    // 关闭弹窗
    closeDialogUser(formName) {
      this.dialogVisible = false
      // 重置表单
      this.$refs[formName].resetFields()
    },
    // 提交新用户
    submitDialogUser() {
      this.$refs.newUserForm.validate(async valid => {
        if (valid) {
          // alert('submit!')
          const { data: res } = await this.$http.post('users', this.newUserForm)

          console.log(res)
          if (res.meta.status !== 201) {
            this.$message.error(res.meta.msg)
          }

          this.dialogVisible = false
          this.$message.success('添加成功')
          this.getUsersList()
        } else {
          // console.log('error submit!!')
          return false
        }
      })
    },
    editUser(row) {
      this.editUserForm.id = row.id
      this.editUserForm.username = row.username
      this.editUserForm.email = row.email
      this.editUserForm.mobile = row.mobile
      this.editdialogVisible = true
    },
    // 提交修改用户信息
    submitEdit() {
      this.$refs.editUserForm.validate(async valid => {
        if (valid) {
          // alert('submit!')
          const { data: res } = await this.$http.put(`users/${this.editUserForm.id}`, this.editUserForm)

          // console.log(res)
          if (res.meta.status !== 200) {
            this.$message.error(res.meta.msg)
          }

          this.editdialogVisible = false
          this.$message.success('更新成功')
          this.getUsersList()
        } else {
          // console.log('error submit!!')
          return false
        }
      })
    },
    closeEditUser(formName) {
      this.editdialogVisible = false
      // 重置表单
      this.$refs[formName].resetFields()
    },
    // 删除用户
    deleteUser(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`users/${id}`)

          // console.log(res)
          if (res.meta.status !== 200) {
            this.$message.error(res.meta.msg)
          }

          this.$message.success('删除成功')
          this.getUsersList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      // console.log(res)
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      }
      this.roleOptions = res.data
    },
    // 分配权限角色
    setUserRole(row) {
      this.userId = row.id
      this.getRolesList()
      this.userRoleForm.username = row.username
      // console.log(row.role_name)
      const role = this.roleOptions.find(item => item.roleName === row.role_name)
      if (typeof role === 'undefined') {
        this.userRoleForm.rid = ''
      } else {
        this.userRoleForm.rid = role.id
      }
      // console.log(row)

      this.roleDialogVisible = true
    },
    // 分配用户角色
    async submitUserRole() {
      const { data: res } = await this.$http.put(`users/${this.userId}/role`, { rid: this.userRoleForm.rid })

      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }

      this.getUsersList()
      this.$message.success(res.meta.msg)

      this.roleDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.users_container {
  .box-card {
    margin-top: 15px;
    .card-header {
      margin-bottom: 15px;
    }
  }
}

.el-button + .el-button {
  margin-left: 0 !important;
}
</style>
